//
//  TYSegmentAnimator.m
//  TYUIKit
//
//  Created by TuyaInc on 2019/2/28.
//

#import "TYSegmentAnimator.h"
@interface TYSegmentAnimator ()

@property (nonatomic, strong) CADisplayLink *displayLink;
@property (nonatomic, assign) CFTimeInterval firstTimestamp;

@end

@implementation TYSegmentAnimator


- (void)dealloc
{
    self.progressCallback = nil;
    self.completeCallback = nil;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        _duration = 0.25;
        _displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(processDisplayLink:)];
    }
    return self;
}

- (void)start {
    [self.displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
}

- (void)stop {
    [self.displayLink invalidate];
    !self.completeCallback ?: self.completeCallback();
}

- (void)processDisplayLink:(CADisplayLink *)sender {
    if (self.firstTimestamp == 0) {
        self.firstTimestamp = sender.timestamp;
    }
    CGFloat percent = (sender.timestamp - self.firstTimestamp)/self.duration;
    if (percent >= 1) {
        !self.progressCallback ?: self.progressCallback(percent);
        [self.displayLink invalidate];
        !self.completeCallback ?: self.completeCallback();
    }else {
        !self.progressCallback ?: self.progressCallback(percent);
    }
}

#pragma mark - util

+ (CGFloat)interpolationFrom:(CGFloat)from to:(CGFloat)to percent:(CGFloat)percent
{
    percent = MAX(0, MIN(1, percent));
    return from + (to - from)*percent;
}

+ (UIColor *)interpolationColorFrom:(UIColor *)fromColor to:(UIColor *)toColor percent:(CGFloat)percent
{
    CGFloat fr, fg, fb = 0;
    CGFloat fa = 1;
    CGFloat tr, tg, tb = 0;
    CGFloat ta = 1;
    [fromColor getRed:&fr green:&fg blue:&fb alpha:&fa];
    [toColor getRed:&tr green:&tg blue:&tb alpha:&ta];
    
    CGFloat red = [self interpolationFrom:fr to:tr percent:percent];
    CGFloat green = [self interpolationFrom:fg to:tg percent:percent];
    CGFloat blue = [self interpolationFrom:fb to:tb percent:percent];
    CGFloat alpha = [self interpolationFrom:fa to:ta percent:percent];
    return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}




@end
